<template>
  <div>
    <div
      :id="id"
      :class="className"
      :style="boxStyles"
    />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from './mixins/resize'
import { MOCKDATA } from './mock/mapdata'
// import AMapLoader from '@amap/amap-jsapi-loader'
// import china from './mock/china_area.json'
// echarts.registerMap('china', china)
// import china from '@/assets/map/js/china.js'
// import chinaSvg from './mock/china.svg'
// const chinaSvg = require('./mock/china.svg')
// import china from './mock/chinaarea.json'
import china from './mock/china.json'
echarts.registerMap('chinaBoundaryline', china)
// import chinaBoundaryline from './mock/china_boundary_line.json'
// echarts.registerMap('chinaBoundaryline', chinaBoundaryline)

export default {
  name: 'MapChart',
  mixins: [resize],
  props: {
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    xLabels: {
      type: Array,
      default: () => {
        return []
      }
    },
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '800px'
    },
    backgroundColor: {
      type: String,
      default: 'transparent'
    }
  },
  data() {
    return {
      chart: null,
      mapOption: [
        {
          name: 'china',
          params: {
            code: '100000_full'
          }
        },
        {
          name: 'chinaBoundaryline',
          params: {
            code: '100000'
          }
        }
      ],
      map: null,
      mapBound: null
    }
  },
  computed: {
    boxStyles() {
      return { height: this.height, width: this.width }
    },
    mapData() {
      var mapBoundFeatures = (this.mapBound && this.mapBound.features) || []
      var mapFeatures = (this.map && this.map.features) || []
      var features = mapBoundFeatures.concat(mapFeatures)
      return {
        ...this.mapBound,
        features: features
      }
    }
    // regions() {
    //   return this.makeTakenRegions(this.map)
    // }
  },
  watch: {
    data() {
      this.initChart()
    }
  },
  beforeMount() {
    // https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json
    // AMapLoader.load({
    //   key: 'c573541ee962147adc05c894114ba8ea', // 刚刚开发者申请哪里的key
    //   plugin: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType']
    // })
    //   .then(AMap => {
    //     this.map = new AMap.Map('container')
    //   })
    //   .catch(e => {
    //     console.log(e)
    //   })
  },
  mounted() {
    // 配置option
    // const url = 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json'
    // var code = '100000'
    // this.$http.geo
    //   .bound({
    //     code: code
    //   })
    //   .then(res => {
    //     this.mapBound = res.data
    //     this.$http.geo
    //       .bound({
    //         code: code + '_full'
    //       })
    //       .then(res => {
    //         this.map = res.data
    //         // echarts.registerMap('china', res.data)
    //         console.log(this.mapData)
    //         echarts.registerMap('chinaBoundaryline', this.mapData)
    //         this.initChart()
    //       })
    //     // echarts.registerMap('china', res.data)
    //     // echarts.registerMap('chinaBoundaryline', res.data)
    //     // this.initChart()
    //   })
    // var svgMap = this.readFile('./mock/china.svg')
    // echarts.registerMap('china', { svg: this.chinaSvg })
    // this.readJson()
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    /**
     * 读取svg文件
     * @filePath:svg文件路径
     */
    readFile: filePath => {
      // 创建一个新的xhr对象
      let xhr = null
      if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest()
      } else {
        // eslint-disable-next-line no-undef
        xhr = new ActiveXObject('Microsoft.XMLHTTP')
      }
      const okStatus = document.location.protocol === 'file' ? 0 : 200
      xhr.open('GET', filePath, false)
      xhr.overrideMimeType('image/svg+xml')
      xhr.send(null)
      return xhr.status === okStatus ? xhr.responseText : null
    },
    loadMapJson() {
      var params = {
        code: '100000_full'
      }
      this.$http.geo.bound(params).then(res => {
        console.log(res.data)
        this.map = res.data
        echarts.registerMap('chinaBoundaryline', res.data)
      })
    },
    makeTakenRegions(map) {
      const { features } = map
      const size = features && features.length
      if (!size) {
        return []
      }

      var regions = []
      for (var i = 0; i < size; i++) {
        var item = features[i]
        const { type } = item.properties
        if (type === '争议') {
          regions.push({
            name: type,
            silent: true,
            itemStyle: {
              color: '#bf0e08',
              borderType: [5, 10],
              borderDashOffset: 5
            }
          })
        } else if (type === '海洋') {
          regions.push({
            name: type,
            silent: true,
            itemStyle: {
              color: '#bf0e08',
              borderType: [5, 10],
              borderDashOffset: 5
            }
          })
        } else if (type === '省界') {
          regions.push({
            name: type,
            silent: true,
            itemStyle: {
              color: '#bf0e08',
              borderType: [5, 10],
              borderDashOffset: 5
            }
          })
        } else if (type === '港澳') {
          regions.push({
            name: type,
            silent: true,
            itemStyle: {
              color: '#bf0e08',
              borderType: [5, 10],
              borderDashOffset: 5
            }
          })
        } else if (type === '国界') {
          regions.push({
            name: type,
            silent: true,
            itemStyle: {
              borderColor: '#389dff',
              borderWidth: 4,
              borderType: 'solid'
            }
          })
        }
      }
      return regions
    },
    initChart() {
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
      this.chart = echarts.init(document.getElementById(this.id))

      var option

      const data = MOCKDATA.data
      const geoCoordMap = MOCKDATA.geoCoordMap
      const convertData = function(data) {
        var res = []
        for (var i = 0; i < data.length; i++) {
          var geoCoord = geoCoordMap[data[i].name]
          if (geoCoord) {
            res.push({
              name: data[i].name,
              value: geoCoord.concat(data[i].value)
            })
          }
        }
        return res
      }
      option = {
        title: {
          text: '全国主要城市空气质量 - 百度地图',
          subtext: 'data from PM25.in',
          sublink: 'http://www.pm25.in',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        geo: {
          map: 'chinaBoundaryline',
          label: {
            // show: false
          },
          roam: false,
          zoom: 1.5,
          // position: ['20%', '50%'],
          center: [104.114129, 37.550339],
          // emphasis: {
          //   show: false
          // },
          itemStyle: {
            // areaColor: '#ff6600',
            areaColor: 'transparent',
            itemStyle: {
              // borderColor: '#389dff'
              // borderWidth: 4,
              // borderType: 'solid',
              borderType: [5, 10],
              borderDashOffset: 5
            }
          },
          regions: [
            {
              name: '中华人民共和国',
              itemStyle: {
                borderColor: 'red',
                borderWidth: 4,
                borderType: 'solid'
              }
            }
          ]
          // regions: this.regions
        },
        series: [
          // {
          //   type: 'map',
          //   map: 'china',
          //   center: [104.114129, 37.550339],
          //   zoom: 1.5,
          //   itemStyle: {
          //     // areaColor: '#0d0059',
          //     areaColor: 'transparent',
          //     borderColor: '#389dff',
          //     borderWidth: 0.5,
          //     borderType: 'dashed',
          //     // borderType: [5, 10],
          //     borderDashOffset: 5
          //   },
          //   emphasis: {
          //     color: 'green',
          //     areaColor: '#17008d',
          //     borderWidth: 0
          //   }
          // },
          {
            name: 'pm2.5',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: convertData(data),
            symbolSize: function(val) {
              return val[2] / 10
            },
            encode: {
              value: 2
            },
            label: {
              formatter: '{b}',
              position: 'right',
              show: false
            },
            emphasis: {
              label: {
                show: true
              }
            }
          },
          {
            name: 'Top 5',
            type: 'effectScatter',
            coordinateSystem: 'bmap',
            data: convertData(
              data
                .sort(function(a, b) {
                  return b.value - a.value
                })
                .slice(0, 6)
            ),
            symbolSize: function(val) {
              return val[2] / 10
            },
            encode: {
              value: 2
            },
            showEffectOn: 'render',
            rippleEffect: {
              brushType: 'stroke'
            },
            label: {
              formatter: '{b}',
              position: 'right',
              show: true
            },
            itemStyle: {
              shadowBlur: 10,
              shadowColor: '#333'
            },
            emphasis: {
              scale: true
            },
            zlevel: 1
          }
        ]
      }
      option && this.chart.setOption(option)

      // var amapComponent = this.chart.getModel().getComponent('amap')
      // console.log('amapComponent', amapComponent)
      // // get the instance of AMap
      // var amap = amapComponent.getAMap()
      // console.log(amap)
      // operations below are the same as amap
      // amap.addControl(new this.$AMap.Scale())
      // amap.addControl(new this.$AMap.ToolBar())
    }
  }
}
</script>
